package com.ruoyi.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.KnowledgeVo;
import org.apache.commons.lang3.StringUtils;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;

import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.Filedata;
import com.ruoyi.system.mapper.FiledataMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.KnowledgepoolMapper;
import com.ruoyi.system.domain.Knowledgepool;
import com.ruoyi.system.service.IKnowledgepoolService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * knowledgepoolService业务层处理
 *
 * @author ruoyi
 * @date 2023-08-22
 */
@Service
public class KnowledgepoolServiceImpl implements IKnowledgepoolService {
    @Autowired
    private KnowledgepoolMapper knowledgepoolMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private FiledataMapper filedataMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询knowledgepool
     *
     * @param id knowledgepool主键
     * @return knowledgepool
     */
    @Override
    public Knowledgepool selectKnowledgepoolById(Long id) {
        return knowledgepoolMapper.selectKnowledgepoolById(id);
    }

    /**
     * 查询knowledgepool列表
     *
     * @param knowledgepool knowledgepool
     * @return knowledgepool
     */
    @Override
    public List<Knowledgepool> selectKnowledgepoolList(Knowledgepool knowledgepool) {
        List<Knowledgepool> list = knowledgepoolMapper.selectKnowledgepoolList(knowledgepool);
        return list;
    }


    /**
     * 新增knowledgepool
     *
     * @param knowledgepool knowledgepool
     * @return 结果
     * return url：http://localhost:8087/profile/upload/2023/08/23/o_panda_20230823170610A001.jpg
     * reutrn fileName：/profile/upload/2023/08/23/o_panda_20230823170610A001.jpg
     * reutrn newFileName：o_panda_20230823170610A001.jpg
     * return originalFilename：o_panda.jpg
     */

    @Override
    @Transactional
    public int insertKnowledgepool(KnowledgeVo knowledgepool) {
        SysDept sysDept = deptMapper.selectDeptById(knowledgepool.getDeptId());
        SysDept sysDept1 = deptMapper.selectDeptById(sysDept.getParentId());
        knowledgepool.setDept(sysDept1.getDeptName() + "-->" + sysDept.getDeptName());
        SysUser sysUser = sysUserMapper.selectUserById(ShiroUtils.getUserId());
        knowledgepool.setFirstPinYin(sysUser.getFirstPinYin());

        String depLString = "";
        switch (knowledgepool.getPermissionType()) {
            case "项目类":
                if (sysDept.getGrade() == 1) {
                    depLString = deptMapper.findAllByGrade(null).stream()
                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                } else if (sysDept.getGrade() == 2) {
                    depLString = deptMapper.selectChildrenDeptById(sysDept.getDeptId()).stream()
                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                } else {
                    depLString = deptMapper.selectChildrenDeptById(sysDept.getParentId()).stream()
                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                }
                knowledgepool.setDeptList(depLString);
                break;
            case "公开类":
                depLString = deptMapper.findAllByGrade(null).stream()
                        .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                knowledgepool.setDeptList(depLString);
                break;
            case "部门类":
                knowledgepool.setDeptList(String.valueOf(sysDept.getDeptId()));
                break;
            case "客户类":
                // 获取当前用户的部门ID
                Long currentDeptId = ShiroUtils.getUserId();
                SysUser currentUser = sysUserMapper.selectUserById(currentDeptId);
                Long userDeptId = currentUser.getDeptId();

                // 如果前端已经传入了deptList，则在其中添加当前用户的部门ID
                List<Long> deptIds = new ArrayList<>();
                if (StringUtils.isNotBlank(knowledgepool.getDeptList())) {
                    for (String id : knowledgepool.getDeptList().split(",")) {
                        deptIds.add(Long.parseLong(id));
                    }
                }

                // 确保当前用户的部门ID被包含在内
                if (!deptIds.contains(userDeptId)) {
                    deptIds.add(userDeptId);
                }
                // 将deptIds转换为字符串
                depLString = String.join(",", deptIds.stream().map(String::valueOf).collect(Collectors.toList()));
                knowledgepool.setDeptList(depLString);
                break;
        }
        int i = knowledgepoolMapper.insertKnowledgepool(knowledgepool);

        if (knowledgepool.getType().equals(2L)) {
            List<Filedata> filedata = new ArrayList<>();
            int length = knowledgepool.getFileNames().split(",").length;

            String[] urls = knowledgepool.getUrls().split(",");
            String[] fileNames = knowledgepool.getFileNames().split(",");
            String[] newFileNames = knowledgepool.getNewFileNames().split(",");
            String[] originalFilenames = knowledgepool.getOriginalFilenames().split(",");
            Long kid = knowledgepoolMapper.findId();

            // 假设需要创建多个Filedata对象
            for (int m = 0; m < length; m++) {
                Filedata filedatum = new Filedata(); // 实例化对象

                // 设置属性
                filedatum.setType(FileUtils.getFileExtension(fileNames[m]));
                filedatum.setKid(kid); // 确保生成唯一ID
                filedatum.setFileUrl(urls[m]);
                filedatum.setFileName(fileNames[m]);
                filedatum.setFileNewfilename(newFileNames[m]);
                filedatum.setFileOriginalfilename(originalFilenames[m]);
                try {
                    File file = new File(RuoYiConfig.getUploadPath() + fileNames[m].replace("/profile/upload", ""));
                    filedatum.setData(FileUtils.getFileToByte(file));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
                filedataMapper.insertFiledata(filedatum);
            }


        }
        return i;
//        return knowledgepoolMapper.insertKnowledgepool(knowledgepool);








    }
//    public int insertKnowledgepool(Knowledgepool knowledgepool) {
//        SysDept sysDept = deptMapper.selectDeptById(knowledgepool.getDeptId());
//        SysDept sysDept1 = deptMapper.selectDeptById(sysDept.getParentId());
//        knowledgepool.setDept(sysDept1.getDeptName() + "-->" + sysDept.getDeptName());
//        SysUser sysUser = sysUserMapper.selectUserById(ShiroUtils.getUserId());
//        knowledgepool.setFirstPinYin(sysUser.getFirstPinYin());
//
//        String depLString = "";
//        switch (knowledgepool.getPermissionType()) {
//            case "项目类":
//                if (sysDept.getGrade() == 1) {
//                    depLString = deptMapper.findAllByGrade(null).stream()
//                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                } else if (sysDept.getGrade() == 2) {
//                    depLString = deptMapper.selectChildrenDeptById(sysDept.getDeptId()).stream()
//                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                } else {
//                    depLString = deptMapper.selectChildrenDeptById(sysDept.getParentId()).stream()
//                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                }
//                knowledgepool.setDeptList(depLString);
//                break;
//            case "公开类":
//                depLString = deptMapper.findAllByGrade(null).stream()
//                        .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                knowledgepool.setDeptList(depLString);
//                break;
//            case "部门类":
//                knowledgepool.setDeptList(String.valueOf(sysDept.getDeptId()));
//                break;
//            case "客户类":
//                // 直接使用前端传来的部门列表
//
//                // deptList已经在前端设置好了，不需要额外处理
//                break;
//        }
//
//        return knowledgepoolMapper.insertKnowledgepool(knowledgepool);
//    }

    @Transactional
//    public int insertKnowledgepool(Knowledgepool knowledgepool) {
//        SysDept sysDept = deptMapper.selectDeptById(knowledgepool.getDeptId());
//        SysDept sysDept1 = deptMapper.selectDeptById(sysDept.getParentId());
//        knowledgepool.setDept(sysDept1.getDeptName() + "-->" + sysDept.getDeptName());
//        SysUser sysUser = sysUserMapper.selectUserById(ShiroUtils.getUserId());
//        knowledgepool.setFirstPinYin(sysUser.getFirstPinYin());
//        //todo
//        String depLString = "";
//        switch (knowledgepool.getPermissionType()) {
//            case "项目类":
//                if (sysDept.getGrade() == 1) {
//
//                    depLString = deptMapper.findAllByGrade(null).stream()
//                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                } else if (sysDept.getGrade() == 2) {
//                    depLString = deptMapper.selectChildrenDeptById(sysDept.getDeptId()).stream()
//                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                } else {
//                    depLString = deptMapper.selectChildrenDeptById(sysDept.getParentId()).stream()
//                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                }
//                knowledgepool.setDeptList(depLString);
//                break;
//            case "公开类":
//                depLString = deptMapper.findAllByGrade(null).stream()
//                        .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
//                knowledgepool.setDeptList(depLString);
//                break;
//            case "部门类":
//                knowledgepool.setDeptList(String.valueOf(sysDept.getDeptId()));
//                break;
//
//
//        }
//
//
//        int i = knowledgepoolMapper.insertKnowledgepool(knowledgepool);
//        if (knowledgepool.getType().equals(2L)) {
//            Filedata filedata = new Filedata();
//            filedata.setType(FileUtils.getFileExtension(knowledgepool.getFileName()));
//            filedata.setKid(knowledgepoolMapper.findId());
//            filedata.setFileUrl(knowledgepool.getUrl());
//            filedata.setFileName(knowledgepool.getFileName());
//            filedata.setFileNewfilename(knowledgepool.getNewFileName());
//            filedata.setFileOriginalfilename(knowledgepool.getOriginalFilename());
//
//            try {
//                File file = new File(RuoYiConfig.getUploadPath() + knowledgepool.getFileName().replace("/profile/upload", ""));
//                filedata.setData(FileUtils.getFileToByte(file));
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//            filedataMapper.insertFiledata(filedata);
//        }
//        return i;
//    }
//







    /**
     * 修改knowledgepool
     *
     * @param knowledgepool knowledgepool
     * @return 结果
     */
    @Override
    public int updateKnowledgepool(Knowledgepool knowledgepool) {
        SysDept sysDept = deptMapper.selectDeptById(knowledgepool.getDeptId());
        knowledgepool.setDept(sysDept.getDeptName());
        SysUser sysUser = sysUserMapper.selectUserById(ShiroUtils.getUserId());
        knowledgepool.setFirstPinYin(sysUser.getFirstPinYin());
        String depLString = "";
        switch (knowledgepool.getPermissionType()) {
            case "项目类":
                if (sysDept.getGrade() == 1) {
                    depLString = deptMapper.findAllByGrade(null).stream()
                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                } else if (sysDept.getGrade() == 2) {
                    depLString = deptMapper.selectChildrenDeptById(sysDept.getDeptId()).stream()
                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                } else {
                    depLString = deptMapper.selectChildrenDeptById(sysDept.getParentId()).stream()
                            .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.joining(","));
                }
                knowledgepool.setDeptList(depLString);
                break;
            case "公开类":
                knowledgepool.setDeptList(depLString);
                break;
            case "部门类":
                knowledgepool.setDeptList(String.valueOf(sysDept.getDeptId()));
                break;
        }
        return knowledgepoolMapper.updateKnowledgepool(knowledgepool);
    }

    /**
     * 批量删除knowledgepool
     *
     * @param ids 需要删除的knowledgepool主键
     * @return 结果
     */
    @Override
    public int deleteKnowledgepoolByIds(String ids) {
        List<String> strings = Arrays.asList(Convert.toStrArray(ids));

        return knowledgepoolMapper.deleteKnowledgepoolByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除knowledgepool信息
     *
     * @param id knowledgepool主键
     * @return 结果
     */
    @Override
    public int deleteKnowledgepoolById(Long id) {
        return knowledgepoolMapper.deleteKnowledgepoolById(id);
    }

    @Override
    public Knowledgepool selectKnowledgepoolByIdForDate(Long valueOf) {
        return knowledgepoolMapper.selectKnowledgepoolByIdAndDate(valueOf);
    }

    @Override
    public AjaxResult<Knowledgepool> updateKnowledgepoolLike(Long uid) {
        return knowledgepoolMapper.updateKnowledgepoolLike(uid);
    }


}
